const _ = require('lodash');
const xlsx = require('node-xlsx');
const async = require('async');
const services = require('../../services');

const commonService = services.common;
const getApprovalStatus = (status) => {
  if (status == 0) return '未审批';
  if (status > 0) {
    return '已通过';
  }
  return '已拒绝';
};


const getApproverDisplayValue = (approverInfo) => {
  if (_.isEmpty(approverInfo)) {
    return '';
  }
  if (_.isEmpty(approverInfo.approverEmployeeId)) {
    return '';
  }
  if (!_.isEmpty(approverInfo.approverChineseName)) {
    return `${approverInfo.approverEmployeeId}/${approverInfo.approverChineseName}`;
  }
  return approverInfo.approverEmployeeId;
};

const getDictDisplayValue = (dictList, sysDictList) => {
  if (_.isEmpty(dictList)) {
    return '';
  }
  let result = '';
  _.forEach(dictList, (dict) => {
    _.forEach(sysDictList, (sysItem) => {
      if (dict.costCenter == _.toString(sysItem.id)) {
        result += `${sysItem.name}/`;
      }
    });
  });
  return _.trim(result, '/');
};
module.exports = (req, res, callback) => {
  const fileName = req.query.fileName || `${new Date().toISOString().replace(/-|T|:|/g, '').split('.')[0]}.xlsx`;
  const formTypeRquested = req.query.requestType;
  const { WfRunInstance: formDetailModel, SysDictionary: dictModel } = commonService.getModels();
  const getExportList = (next) => {
    if (!_.isEmpty(formTypeRquested)) { commonService.getList(formDetailModel, { where: { formId: formTypeRquested }, include: ['form', 'flow', { approvalList: ['requester', 'approver'] }, 'owner'] }, next); } else { commonService.getList(formDetailModel, { where: { formId: 1 }, include: ['form', 'flow', { approvalList: ['requester', 'approver'] }, 'owner'] }, next); }
  };
  const getSysDictList = (formDetailList, next) => {
    commonService.getList(dictModel, (error, sysDictList) => next(error, formDetailList, sysDictList));
  };
  const createExcel = (formDetailList, sysDictList, next) => {
    try {
      let theads = ['编号', '类型', '申请人', '申请日期', '采购审阅人', '状态', '法务审阅人', '状态', ' E&C审阅人', '状态', 'ATS审阅人', '状态', '公司印章持有人', '状态', '业务实体', '部门', '是否是会议', '业务名称简述',
        'e-CIR 项目编号', ' 预计的业务开展时间', ' 预计的业务结束时间', '合同总金额', '合同方名称', '确认为新Vendor', 'ACDD', '成本中心', '简要描述'];
      if (formTypeRquested == 2) {
        theads = ['编号', '类型', '申请人', '申请日期', '职位名称', '工作地点', '员工类型', '业务部门1', '业务部门2', '业务部门3', '业务部门4',
          '薪资级别', '用人经理', '人力资源经理', '时间', '状态', '业务审批人', '时间', '状态', 'OPS审批', '时间', '状态', 'TA审批', '时间', '状态'];
      }

      const data = [theads];
      _.forEach(formDetailList, (formDetailItem) => {
        const form = formDetailItem.form();
        const formDetail = formDetailItem.formDetail;
        let approvalList = [];
        if (formDetailItem.formStatus == -99) {
          approvalList = [
            { approverEmployeeId: '', approvalStatus: '' },
            { approverEmployeeId: '', approvalStatus: '' },
            { approverEmployeeId: '', approvalStatus: '' },
            { approverEmployeeId: '', approvalStatus: '' },
          ];
        } else {
          const originApprovalList = formDetailItem.approvalList();
          approvalList = [
            { approverEmployeeId: _.isEmpty(formDetail.approvalStep1Approver) ? '' : formDetail.approvalStep1Approver, approvalStatus: '' },
            { approverEmployeeId: _.isEmpty(formDetail.approvalStep2Approver) ? '' : formDetail.approvalStep2Approver, approvalStatus: '' },
            { approverEmployeeId: _.isEmpty(formDetail.approvalStep3Approver) ? '' : formDetail.approvalStep3Approver, approvalStatus: '' },
            { approverEmployeeId: _.isEmpty(formDetail.approvalStep4Approver) ? '' : formDetail.approvalStep4Approver, approvalStatus: '' },
            { approverEmployeeId: _.isEmpty(formDetail.approvalStep5Approver) ? '' : formDetail.approvalStep5Approver, approvalStatus: '' },
          ];
          let index = 0;
          if (formTypeRquested == 2) {
            _.forEach(originApprovalList, (item) => {
              approvalList[item.approvalStep - 1].approvalStatus = getApprovalStatus(item.approvalStatus);
              approvalList[item.approvalStep - 1].approverChineseName = item.approver().chineseName;
              approvalList[item.approvalStep - 1].approverEmployeeId = item.approverEmployeeId;
              approvalList[item.approvalStep - 1].approvalTime = item.updatedAt;
            });
          } else {
            _.forEach(approvalList, (item) => {
              if (!_.isEmpty(item.approverEmployeeId)) {
                item.approvalStatus = getApprovalStatus(originApprovalList[index].approvalStatus);
                item.approverChineseName = originApprovalList[index].approver().chineseName;
                index++;
              }
            });
          }
        }
        const columnList = [];
        const ownerName = _.isEmpty(formDetailItem.owner()) ? formDetailItem.sys_owner : `${formDetailItem.sys_owner}/${formDetailItem.owner().chineseName}`;
        if (formTypeRquested == 1 || _.isEmpty(formTypeRquested)) {
          columnList.push(formDetailItem.formNumber, form.formChineseName, ownerName, formDetailItem.createdAt,
            getApproverDisplayValue(approvalList[0]), _.isEmpty(approvalList[0]) ? '' : approvalList[0].approvalStatus,
            getApproverDisplayValue(approvalList[1]), _.isEmpty(approvalList[1]) ? '' : approvalList[1].approvalStatus,
            getApproverDisplayValue(approvalList[2]), _.isEmpty(approvalList[2]) ? '' : approvalList[2].approvalStatus,
            getApproverDisplayValue(approvalList[3]), _.isEmpty(approvalList[3]) ? '' : approvalList[3].approvalStatus,
            getApproverDisplayValue(approvalList[4]), _.isEmpty(approvalList[4]) ? '' : approvalList[4].approvalStatus,
            formDetail.legalEntity, formDetail.department, _.toString(formDetail.isMeeting).toUpperCase(), formDetail.activityNameDescription,
            formDetail.projectNumber, formDetail.activityDateStart, formDetail.activityDateEnd, formDetail.totalContractAmount, formDetail.vendorName,
            _.toString(formDetail.isVendor).toUpperCase(), _.toString(formDetail.acdd).toUpperCase(), getDictDisplayValue(formDetail.costCenterAndAmountList, sysDictList), _.unescape(formDetail.briefDescription));
        } else {
          let workingLocation = '';
          if (formDetail.workingLocationProvince != '请选择' && formDetail.workingLocationCity != '请选择') workingLocation = `${formDetail.workingLocationProvince}/${formDetail.workingLocationCity}`;
          if (formDetail.workingLocationCity == '请选择' && formDetail.workingLocationProvince != '请选择') workingLocation = `${formDetail.workingLocationProvince}`;
          if (formDetail.workingLocationCity != '请选择' && formDetail.workingLocationProvince == '请选择') workingLocation = `${formDetail.workingLocationCity}`;
          columnList.push(formDetailItem.formNumber, form.formChineseName, ownerName, formDetailItem.createdAt, formDetail.positionTitle,
            workingLocation, formDetail.employeeTypeName,
            _.isEmpty(formDetail.businessNode1Code) ? '' : formDetail.businessNode1Code,
            _.isEmpty(formDetail.businessNode2Code) ? '' : formDetail.businessNode2Code,
            _.isEmpty(formDetail.businessNode3Code) ? '' : formDetail.businessNode3Code,
            _.isEmpty(formDetail.businessNode4Code) ? '' : formDetail.businessNode4Code,
             _.isEmpty(formDetail.jobNumber) ? '' : formDetail.jobNumber, `${formDetail.hiringManager.employeeId}/${formDetail.hiringManager.chineseName}`,
            getApproverDisplayValue(approvalList[0]), _.isEmpty(approvalList[0]) ? '' : approvalList[0].approvalTime, _.isEmpty(approvalList[0]) ? '' : approvalList[0].approvalStatus,
            getApproverDisplayValue(approvalList[1]), _.isEmpty(approvalList[1]) ? '' : approvalList[1].approvalTime, _.isEmpty(approvalList[1]) ? '' : approvalList[1].approvalStatus,
            getApproverDisplayValue(approvalList[2]), _.isEmpty(approvalList[2]) ? '' : approvalList[2].approvalTime, _.isEmpty(approvalList[2]) ? '' : approvalList[2].approvalStatus,
            getApproverDisplayValue(approvalList[3]), _.isEmpty(approvalList[3]) ? '' : approvalList[3].approvalTime, _.isEmpty(approvalList[3]) ? '' : approvalList[3].approvalStatus);
        }
        data.push(columnList);
      });

      const buffer = xlsx.build([{ name: 'mySheetName', data }]);
      next(null, buffer);
    } catch (error) {
      return next(error);
    }
  };
  async.waterfall([getExportList, getSysDictList, createExcel], (error, buffer) => {
    if (error) return callback(error);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader('Content-Disposition', `attachment; filename = ${fileName}`);
    res.end(buffer, 'binary');
  });
};
